import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {Button, Form, Input} from "antd";
import {getCaptchaImg} from "@/services/login";
import {Link, useNavigate} from "react-router-dom";
import {ILoginPayload} from "@/stores/actions/loginActions";
import './index.scss'
import {IAppState} from "@/stores/reducers";
import {getToken} from "@/utils/auth";

interface ILoginProps {
}

const Login: React.FC<ILoginProps> = props => {
    const dispatch = useDispatch()
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [codeUrl, setCodeUrl] = useState<string>('')
    const [uuid, setUuid] = useState<string>('')
    const [register] = useState<boolean>(false)
    const loading = useSelector<IAppState, boolean>(state => state.login.login.loading)
    const success = useSelector<IAppState, boolean>(state => state.login.login.success)
    useEffect(() => {
        if (getToken()) {
            navigate('/')
        }
        getCode()
        document.title = '登陆-' + process.env.REACT_APP_BASE_TITLE
    }, []);
    useEffect(() => {
        if (!loading && !success) {
            getCode()
        }
    }, [loading, success])
    const handleLogin = async () => {
        if (loading) return
        try {
            const values = await form.validateFields();
            const params = {} as ILoginPayload
            for (const [key, val] of Object.entries(values)) {
                params[key] = (val as string).trim()
            }
            params.uuid = uuid
            dispatch({type: 'LOGIN', payload: {...params}});
        } catch (errorInfo) {
            console.log('Failed:', errorInfo);
        }
    }

    const getCode = async () => {
        const res = await getCaptchaImg() as any
        setCodeUrl('data:image/gif;base64,' + res.img)
        setUuid(res.uuid)
    }

    return (
        <div className='loginBox'>
            <div className="content">
                <div className="formCard">
                    <div className="left">
                        <img alt="" src="@/assets/images/login.png"/>
                    </div>
                    <Form form={form} className="login-form">
                        <img
                            alt=""
                            className="head-Logo"
                            src="@/assets/images/dmz_logo.png"
                        />
                        <h3 className="title">登陆</h3>
                        <div className="item">
                            <Form.Item
                                name="username"
                                label="账号"
                                rules={[{required: true, message: '输入不能为空'}]}
                            >
                                <Input
                                    className="login-form-input"
                                    type='text'
                                    placeholder="请输入账号"
                                />
                            </Form.Item>
                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[{required: true, message: '输入不能为空'}]}
                            >
                                <Input
                                    className="login-form-input"
                                    type='password'
                                    placeholder="请输入密码"
                                />
                            </Form.Item>
                            <div className="imgBox">
                                <Form.Item
                                    name="code"
                                    rules={[{required: true, message: '输入不能为空'}]}
                                >
                                    <Input
                                        className="login-form-input"
                                        placeholder="请输入验证码"
                                    />
                                </Form.Item>
                                <div className="login-code">
                                    <img src={codeUrl} className="login-code-img" onClick={getCode}/>
                                </div>
                            </div>
                            <div className="btnBox">
                                <Button loading={loading} size='middle' type="primary" onClick={handleLogin}>
                                    {
                                        loading ? '登 录 中...' : '登 录'
                                    }
                                </Button>
                                {
                                    register && (
                                        <div style={{float: 'right'}}>
                                            <Link className='link-type' to='/register'>立即注册</Link>
                                        </div>
                                    )
                                }
                            </div>
                        </div>
                    </Form>
                </div>
            </div>
        </div>
    );
};


// 连接组件并导出
export default Login;